# -*- coding: UTF-8 -*-
import json
import time
import pytest
import allure
import os
from application.app_server_api import OperateApp
from application.general_create import SPACE_ID, APP_ID, COOKIE, USER_ID, SPACE_NAME, AUTO_CREATE, ENTERPRISE_ID
from application.space_server_api import SpaceServer
from application.system_server_api import SystemServer, parsing
from pyLib.databaseManage import SYS_DATABASE
from pyLib.LogManage import LOG
from tools.handle_path import data_path


@pytest.fixture(scope="session", autouse=AUTO_CREATE)
def init_fixture():
    # 获取headers
    headers = {"cookie": COOKIE, "language": "zh-cn", "app": APP_ID, "space": SPACE_ID, "user": USER_ID}
    filepath = os.path.join(data_path,  'import_data', 'Heytea.zip')
    # 导入元素
    OperateApp(headers).import_elements(filepath, "0", check_status=True)
    yield
    # 删除和空间相关的APP
    result_app = SYS_DATABASE.execute_sql(
        f"select app_name from sp_app_info where space_id='{SPACE_ID}' and id='{APP_ID}'")
    r = SpaceServer(headers).remove_app(params={"appId": APP_ID, "appName": result_app[0][0]},
                                        drop_table=True)
    allure.attach(r.text, f"删除{APP_ID}应用", allure.attachment_type.TEXT)
    del headers["app"]
    r = SystemServer(headers).email_send()  # 获取验证码
    LOG.info(f"发送删除空间验证码:{r.text}")
    requests = {
        "code": parsing(SPACE_NAME),
        "codeType": "EMAIL",
        "spaceName": SPACE_NAME,
        "language": "zh-cn",
        "enterprise-id": ENTERPRISE_ID
    }
    LOG.info(f"获取邮箱验证码：{requests.get('code')}")
    # 删除空间
    r = SystemServer(headers).space_del(requests, del_space_id=SPACE_ID)
    allure.attach(r.text, f"删除{SPACE_ID}空间", allure.attachment_type.TEXT)
